package dper.study.codes.common.tailed;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Created by leichen on 2017/5/11.
 * 高并发的LinkedHashMap
 */
public class MyTailedLinkedHashMap extends LinkedHashMap<String,String> {

    private AtomicLong lastPutStamp = new AtomicLong(System.currentTimeMillis());

    private int interval = 10 ;

    private int maxpairs = 500000 ;

    public MyTailedLinkedHashMap(int cap){

        super(cap, 0.75f, true);
    }

    @Override
    public String put(String key,String value){
        //不能插入过快，否则高并发下会发生性能问题
        //需要redis辅助接住未插入的
        if(System.currentTimeMillis() >= lastPutStamp.getAndSet(System.currentTimeMillis()+interval)){
            return super.put(key,value) ;
        }else{
            return null;
        }
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<String, String> eldest) {
        return super.size() > maxpairs;
    }

    @Override
    public String toString(){
        return "linkedhashmap cache Size = " + this.size() + "/"
                + maxpairs;
    }



}
